﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace PremisPublisher.Common
{
    public class ValidateXmlFile
    {
        static StringBuilder sb = null;
        public static string ValidateXml(string schemaFile, string xmlFile)
        {

            var namespaceUrl = "";

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.ValidationType = ValidationType.Schema;
            settings.Schemas.Add(namespaceUrl, schemaFile);
            settings.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(settings_ValidationEventHandler);

            string errorMessage = "这不是一个合乎规范的数据文件";
            sb = new StringBuilder();

            XmlReader reader = XmlReader.Create(xmlFile, settings);
            try
            {
                reader.MoveToContent();
                while (reader.Read())
                {
                    if (reader.NodeType == XmlNodeType.Document && reader.NamespaceURI != namespaceUrl)
                    {
                        return errorMessage;
                        break;
                    }
                }
            }
            catch (XmlException ex)
            {
                sb.AppendFormat("{0}", ex.Message);
            }
            finally
            {
                reader.Close();
            }

            if (sb.Length == 0)
                return "true";
            else
                return sb.ToString();

        }
        static void settings_ValidationEventHandler(object sender, System.Xml.Schema.ValidationEventArgs e)
        {
            sb.AppendFormat("{0}", e.Message);
        }
    }
}
